package me.qingy.shiro.service;

import me.qingy.core.entity.UserOnline;
import me.qingy.core.service.UserOnlineService;
import me.qingy.shiro.session.OnlineSession;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 会话db操作处理
 *
 * @author qingy
 * @since 2021-05-08
 */
@Component
public class ShiroService {

    @Autowired
    private UserOnlineService onlineService;

    /**
     * 删除会话
     */
    public void deleteSession(OnlineSession onlineSession) {
        onlineService.removeById(String.valueOf(onlineSession.getId()));
    }

    /**
     * 获取会话信息
     */
    public Session getSession(Serializable sessionId) {
        UserOnline userOnline = onlineService.getById(String.valueOf(sessionId));
        return userOnline == null ? null : createSession(userOnline);
    }

    public Session createSession(UserOnline userOnline) {
        OnlineSession onlineSession = new OnlineSession();
        if (userOnline != null) {
            onlineSession.setId(userOnline.getSessionId());
            onlineSession.setHost(userOnline.getIpaddr());
            onlineSession.setLoginName(userOnline.getLoginName());
            onlineSession.setStartTimestamp(userOnline.getStartTimestamp());
            onlineSession.setLastAccessTime(userOnline.getLastAccessTime());
            onlineSession.setTimeout(userOnline.getExpireTime());
        }
        return onlineSession;
    }
}
